﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OSGeo.MapGuide;
using System.Data;
using AjaxControlToolkit;
using System.Drawing;
using System.Configuration;
using System.Xml;
using NegevGas;
using NegevGas.SdfEditor;
using System.Collections.Specialized;
namespace NegevGas.Extensions.FeatureEdit
{


    public class editPropertyFieldTemplate : ITemplate
    {
        List<Control> c = new List<Control>();

        public editPropertyFieldTemplate(FeatProperty p) : this(p, string.Empty) { }

        public editPropertyFieldTemplate(FeatProperty p, string sdfFile)
        {
            if (p.IsReadOnly == true)
            {
                Label lbl = new Label();
                lbl.Text = p.Value.ToString();
                lbl.ID = p.Name;
                c.Add(lbl);
            }
            else if (p.AviableValues != null)
            {
                DropDownList ddl = new DropDownList();
                ddl.ID = p.Name;
                for (int i = 0; i < p.AviableValues.Count; i++)
                {
                    ddl.Items.Add(new ListItem(p.AviableValues[i]));
                }
                ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByText(p.Value.ToString()));
                ddl.Style["width"] = "150px";
                c.Add(ddl);

                if (!string.IsNullOrEmpty(sdfFile))
                {
                    LiteralControl lnkEditConstraint = new LiteralControl();
                    lnkEditConstraint.Text = string.Format("<span class='buttonP' onclick='ShowSdfEditorDialog(\"{0}\", \"_FeatureCard_{0}\")'>+</span>", HttpUtility.UrlEncode(p.Name));
                    ddl.Style["width"] = "130px";
                    c.Add(lnkEditConstraint);
                }
            }
            else if (p.LookUpValues != null && p.LookUpValues.Count != 0)
            {
                DropDownList ddl = new DropDownList();
                ddl.ID = p.Name;
                foreach (var item in p.LookUpValues)
                {
                    ddl.Items.Add(new ListItem(item.Value, item.Key.ToString()));
                }
                if (p.Value == null) ddl.SelectedIndex = 0;
                else ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(p.Value.ToString()));
                ddl.Style["width"] = "150px";
                c.Add(ddl);

                if (!string.IsNullOrEmpty(sdfFile))
                {
                    LiteralControl lnkEditConstraint = new LiteralControl();
                    lnkEditConstraint.Text = string.Format("<span class='buttonP' onclick='ShowSdfEditorDialog(\"{0}\", \"_FeatureCard_{0}\")'>+</span>", HttpUtility.UrlEncode(p.Name));
                    ddl.Style["width"] = "130px";
                    c.Add(lnkEditConstraint);
                }
            }
            else if (p.PropertyType == MgPropertyType.DateTime)
            {
                TextBox tb = new TextBox();
                tb.ID = p.Name;
                if (p.Value != null)
                    tb.Text = p.Value.ToString();

                tb.Style.Add("margin-left", "2px");
                tb.ToolTip = "dd/MM/yyyy";
                tb.Attributes.Add("dir", "ltr");
                tb.Style.Add("text-align", "right");
                c.Add(tb);
                if (p.Alias == "תאריך עדכון" || p.Alias == "עדכון אחרון")
                {
                    tb.Enabled = false;
                    return;
                }
                tb.CssClass = "dateField";
                ImageButton btnPicker = new ImageButton();
                btnPicker.ID = string.Format("{0}_btnPicker", p.Name);
                btnPicker.ImageUrl = "~/Images/calendar.jpg";
                btnPicker.ImageAlign = ImageAlign.Middle;
                btnPicker.Height = new Unit("16px");
                c.Add(btnPicker);

                CalendarExtender ext = new CalendarExtender();
                ext.PopupButtonID = btnPicker.ID;
                ext.TargetControlID = tb.ID;
                ext.Format = "dd/MM/yyyy";
                ext.CssClass = "cal_Theme1";
                ext.ID = string.Format("{0}_ext", p.Name);
                ext.Enabled = true;
                c.Add(ext);

                MaskedEditExtender meExt = new MaskedEditExtender();
                meExt.Mask = "99/99/9999";
                meExt.InputDirection = MaskedEditInputDirection.RightToLeft;
                meExt.TargetControlID = tb.ID;
                meExt.MaskType = MaskedEditType.Date;
                meExt.ID = string.Format("{0}_MaskEditExt", p.Name);
                c.Add(meExt);

            }
            else if (p.PropertyType == MgPropertyType.Boolean)
            {
                CheckBox cb = new CheckBox();
                cb.ID = p.Name;
                if (p.Value == null) p.Value = "False";
                cb.Checked = bool.Parse(p.Value.ToString());
                c.Add(cb);
            }
            else
            {
                TextBox tb = new TextBox();
                tb.ID = p.Name;
                if (p.Value != null)
                    tb.Text = p.Value.ToString();
                else
                    tb.Text = string.Empty;
                c.Add(tb);
            }
        }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            foreach (Control ctrl in c)
            {
                container.Controls.Add(ctrl);
            }
        }

        #endregion
    }
    public class viewPropertyFieldTemplate : ITemplate
    {
        List<Control> c = new List<Control>();

        public viewPropertyFieldTemplate(FeatProperty p)
        {
            if (p.PropertyType == MgPropertyType.Boolean)
            {
                CheckBox cb = new CheckBox();
                cb.ID = p.Name;
                cb.Checked = bool.Parse(p.Value.ToString());
                cb.Enabled = false;
                c.Add(cb);
                Label lbl = new Label();
                lbl.Text = cb.Checked ? "(כן)" : "(לא)";
                lbl.ID = "lbl_" + p.Name;
                c.Add(lbl);
            }
            else
            {
                Label lbl = new Label();
                if (p.Value != null)
                {
                    if (p.LookUpValues != null && p.LookUpValues.Count > 0)
                    {
                        var vals = p.LookUpValues.Where(x => x.Key == (int)p.Value);
                        foreach (var v in vals)
                        {
                            Label lblTxt = new Label();
                            lblTxt.Text = v.Value;
                            lblTxt.ID = p.Name + "_txt";
                            lbl.Visible = false;
                            c.Add(lblTxt);
                            break;
                        }
                    }
                    lbl.Text = p.Value.ToString();
                }
                lbl.ID = p.Name;
                //lbl.DataBinding += new EventHandler(lbl_DataBinding);
                c.Add(lbl);
            }
        }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            foreach (Control ctrl in c)
            {
                container.Controls.Add(ctrl);
            }
        }

        #endregion
    }
    public class editFooterTemplate : ITemplate
    {
        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            LinkButton lbUpdate = new LinkButton();
            lbUpdate.ID = "linkUpdateCmd";
            lbUpdate.Text = "אישור";
            lbUpdate.OnClientClick = "return confirm('אתם בטוחים שברצונכם לשמור שינויים?');";
            lbUpdate.CausesValidation = false;
            lbUpdate.CommandName = "Update";

            container.Controls.Add(lbUpdate);

            container.Controls.Add(new LiteralControl("&nbsp;"));

            LinkButton lbCancel = new LinkButton();
            lbCancel.ID = "linkCancelCmd";
            lbCancel.Text = "ביטול";
            lbCancel.CausesValidation = false;
            lbCancel.CommandName = "Cancel";
            container.Controls.Add(lbCancel);

        }

        #endregion
    }
    public class viewFooterTemplate : ITemplate
    {
        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            LinkButton lbEdit = new LinkButton();
            lbEdit.ID = "linkEditCmd";
            lbEdit.Text = "עדכון";
            lbEdit.CausesValidation = false;
            lbEdit.CommandName = "Edit";
          //  lbEdit.CssClass = "clsShortButton";
            container.Controls.Add(lbEdit);
        }

        #endregion
    }


    public partial class FeatureEdit : System.Web.UI.Page
    {

        FeatPropertyCollection fpCollection;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _FeatureCard.ModeChanging += new DetailsViewModeEventHandler(_FeatureView_ModeChanging);
            _FeatureCard.ItemUpdating += new DetailsViewUpdateEventHandler(_FeatureCard_ItemUpdating);
            _FeatureCard.DataBound += new EventHandler(_FeatureCard_DataBound);
        }
        public NameValueCollection GetRequestParameters()
        {
            if ("POST" == HttpContext.Current.Request.HttpMethod)
            {
                return HttpContext.Current.Request.Form;
            }
            else
            {
                return HttpContext.Current.Request.QueryString;
            }
        }
        bool iseditmode = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                int mgProjectId;
               
               

                if (!IsPostBack)
                {

                    if (GetRequestParameters()["isedit"] == "1")
                    {
                        iseditmode = true;
                        ViewState.Add("isedit", GetRequestParameters()["isedit"]);

                    }
                    else
                    {
                        iseditmode = false;
                       // ViewState.Add("isedit", GetRequestParameters()["isedit"]);
                       
                    }
                    // if (!int.TryParse(Request["mgProjectId"], out mgProjectId)) return;
                    //    ViewState.Add("mgProjectId", mgProjectId);
                    //    Session["mgSessionId"] = Request["SESSION"];
                    //    ViewState.Add("mgSessionId", Request["SESSION"]);
                   ;
                   if (!int.TryParse(GetRequestParameters()["mgProjectId"], out mgProjectId)) return;
                    ViewState.Add("mgProjectId", mgProjectId);
                    Session["mgSessionId"] = GetRequestParameters()["SESSION"];
                    ViewState.Add("mgSessionId", GetRequestParameters()["SESSION"]);
                }
                else
                {
                    if (Session["mgSessionId"] == null)
                    {
                        Session["mgSessionId"] = ViewState["mgSessionId"];
                    }
                    mgProjectId = (int)ViewState["mgProjectId"];
                }
                SiteUtilities siteUtilities = new SiteUtilities(new MapSettings(mgProjectId));
                if (!IsPostBack)
                {
                    MgLayer layer = (MgLayer)siteUtilities.Selection.GetLayers()[0];
                    string Filter = siteUtilities.Selection.GenerateFilter(layer, layer.FeatureClassName);
                    if (Filter == "")
                    {
                        Response.Write("האופציה הזו לא קיימת לפרית הזה.");
                        Response.End();
                    }
                    ViewState.Add("LayerName", layer.Name);
                    ViewState.Add("Filter", Filter);
                    getSdfFile(siteUtilities);
                }

                fpCollection = new FeatPropertyCollection(siteUtilities, ViewState["LayerName"].ToString(), ViewState["Filter"].ToString());
                if (ViewState["SdfFile"] != null)
                {
                    SdfFileName.Value = ViewState["SdfFile"].ToString();
                    fpCollection.FillLookUpValues(ViewState["SdfFile"].ToString());
                }


                _HeaderText.Text = fpCollection.LegendLabel;
                _FeatureCard.Fields.Clear();

                foreach (var p in fpCollection.PropertiesCollection)
                {
                    TemplateField myTemplate = new TemplateField();
                    editPropertyFieldTemplate f = new editPropertyFieldTemplate(p.Value, ViewState["SdfFile"].ToString());
                    viewPropertyFieldTemplate viewTmpl = new viewPropertyFieldTemplate(p.Value);
                    myTemplate.EditItemTemplate = f;
                    myTemplate.ItemTemplate = viewTmpl;
                    myTemplate.HeaderText = p.Value.Alias;
                    _FeatureCard.Fields.Add(myTemplate);
                }
                if (ViewState["isedit"] !=null)
                {

                
                TemplateField myFooterTemplate = new TemplateField();


                viewFooterTemplate viewFooter = new viewFooterTemplate();
                editFooterTemplate editFooter = new editFooterTemplate();
                myFooterTemplate.ItemTemplate = viewFooter;
                myFooterTemplate.EditItemTemplate = editFooter;
                myFooterTemplate.ShowHeader = false;
              //  myFooterTemplate.ItemStyle.BackColor = Color.FromArgb(255, 255, 192);
                _FeatureCard.Fields.Add(myFooterTemplate);
            }
                _FeatureCard.AutoGenerateRows = false;
                _FeatureCard.DataSource = fpCollection.FeatureDataSet;
                _FeatureCard.DataBind();
            }
            catch (InvalidOperationException ex)
            {
                ErrorLog log = new ErrorLog(ConfigurationManager.ConnectionStrings["ErrorLogConnectionString"].ConnectionString);
                log.AddError(ex);

            }
        }
        private void getSdfFile(SiteUtilities siteUtilities)
        {

            string featureSourceId = siteUtilities.Map.GetLayers().GetItem(ViewState["LayerName"].ToString()).FeatureSourceId;
            string fileName = string.Empty;
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("~/XML/SDF_Files.xml"));
            XmlNode node = doc.SelectSingleNode(string.Format("/root/FeatureSource[@ID=\"{0}\"]", featureSourceId));
            if (node != null)
            {
                fileName = node.Attributes["file"].InnerText;
                SdfEditorPanel.Visible = true;
            }

            ViewState.Add("SdfFile", fileName);
        }
        void _FeatureView_ModeChanging(object sender, DetailsViewModeEventArgs e)
        {
            DetailsView dv = (DetailsView)sender;
            dv.ChangeMode(e.NewMode);
            dv.DataBind();
        }
        void _FeatureCard_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
            DetailsView dv = (DetailsView)sender;
            DataRow r = ((DataRowView)dv.DataItem).Row;
            if (!e.Cancel)
            {
                List<string> NewValues = new List<string>();
                for (int i = 0; i < dv.Rows.Count; i++)
                {
                    for (int j = 0; j < dv.Rows[i].Cells.Count; j++)
                    {
                        for (int k = 0; k < dv.Rows[i].Cells[j].Controls.Count; k++)
                        {
                            Control control = dv.Rows[i].Cells[j].Controls[k];
                            if (control.GetType() == typeof(TextBox))
                            {
                                TextBox tb = (TextBox)control;
                                fpCollection.PropertiesCollection[tb.ID].Value = tb.Text;
                                r[tb.ID] = tb.Text;
                            }
                            else if (control.GetType() == typeof(DropDownList))
                            {
                                DropDownList ddl = (DropDownList)control;
                                fpCollection.PropertiesCollection[ddl.ID].Value = ddl.SelectedValue;
                                r[ddl.ID] = ddl.SelectedItem;
                            }
                            else if (control.GetType() == typeof(CheckBox))
                            {
                                CheckBox cb = (CheckBox)control;
                                fpCollection.PropertiesCollection[cb.ID].Value = cb.Checked;
                                r[cb.ID] = cb.Checked;
                            }
                        }
                    }
                }
            }
            fpCollection.UpdateFeature(ViewState["Filter"].ToString());
            dv.ChangeMode(DetailsViewMode.ReadOnly);
            dv.DataBind();
        }
        void _FeatureCard_DataBound(object sender, EventArgs e)
        {
            DetailsView dv = sender as DetailsView;
            _FeatureCard.DataSource = fpCollection.FeatureDataSet;
            DataRowView row = dv.DataItem as DataRowView;

            foreach (var p in fpCollection.PropertiesCollection)
            {
                Control c = _FeatureCard.FindControl(p.Key);
                if (c == null) continue;
                if (c.GetType() == typeof(TextBox))
                {
                    TextBox tb = c as TextBox;
                    tb.Text = DataBinder.Eval(_FeatureCard.DataItem, p.Key, "{0}");
                }
                else if (c.GetType() == typeof(Label))
                {
                    Label lbl = c as Label;
                    if (p.Value.Value != null)
                        lbl.Text = p.Value.Value.ToString();
                }
                else if (c.GetType() == typeof(CheckBox))
                {
                    CheckBox cb = c as CheckBox;
                    cb.Checked = bool.Parse(p.Value.Value.ToString());
                    Label lbl1 = (Label)_FeatureCard.FindControl("lbl_" + p.Key);
                    if (lbl1 != null)
                    {
                        lbl1.Text = cb.Checked ? "(כן)" : "(לא)";
                    }
                }
                Control c_txt = _FeatureCard.FindControl(p.Key + "_txt");
                if (c_txt != null)
                {
                    var vals = p.Value.LookUpValues.Where(x => x.Key == (int)Convert.ToInt32(p.Value.Value));
                    foreach (var v in vals)
                    {
                        Label lblTxt = c_txt as Label;
                        lblTxt.Text = v.Value;
                        break;
                    }
                }
            }
        }
    }
}